#!/bin/bash

# DevOps SmartBot - 全服务测试脚本
# 测试所有微服务的健康状态和核心功能

set -e

echo "╔════════════════════════════════════════════════════════════╗"
echo "║          DevOps SmartBot - 全服务测试                      ║"
echo "╚════════════════════════════════════════════════════════════╝"
echo ""

# 颜色定义
GREEN='\033[0;32m'
RED='\033[0;31m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

# API Gateway地址
API_GATEWAY="http://localhost:8080"

# 测试结果统计
TOTAL_TESTS=0
PASSED_TESTS=0
FAILED_TESTS=0

# 测试函数
test_endpoint() {
    local name=$1
    local method=$2
    local url=$3
    local expected_code=${4:-200}
    local data=${5:-""}

    TOTAL_TESTS=$((TOTAL_TESTS + 1))

    if [ -z "$data" ]; then
        response=$(curl -s -w "\n%{http_code}" -X $method "$url" 2>/dev/null || echo "000")
    else
        response=$(curl -s -w "\n%{http_code}" -X $method -H "Content-Type: application/json" -d "$data" "$url" 2>/dev/null || echo "000")
    fi

    http_code=$(echo "$response" | tail -n1)
    body=$(echo "$response" | sed '$d')

    if [ "$http_code" = "$expected_code" ]; then
        echo -e "${GREEN}✓${NC} $name"
        PASSED_TESTS=$((PASSED_TESTS + 1))
        return 0
    else
        echo -e "${RED}✗${NC} $name (Expected: $expected_code, Got: $http_code)"
        FAILED_TESTS=$((FAILED_TESTS + 1))
        return 1
    fi
}

# 1. 测试基础服务
echo "【1. 基础服务健康检查】"
test_endpoint "API Gateway Health" "GET" "$API_GATEWAY/healthz"
test_endpoint "API Gateway Version" "GET" "$API_GATEWAY/api/version"
echo ""

# 2. 测试告警服务
echo "【2. Alert Service】"
test_endpoint "List Alerts" "GET" "$API_GATEWAY/api/alerts"
test_endpoint "Alert Statistics" "GET" "$API_GATEWAY/api/alerts/statistics"
echo ""

# 3. 测试工单服务
echo "【3. Ticket Service】"
test_endpoint "List Tickets" "GET" "$API_GATEWAY/api/tickets"
test_endpoint "Ticket Statistics" "GET" "$API_GATEWAY/api/tickets/statistics"

# 创建测试工单
echo -n "  Creating test ticket... "
CREATE_TICKET_DATA='{
  "title": "Test Ticket from Script",
  "description": "This is a test ticket created by the test script",
  "priority": "medium"
}'
TICKET_RESPONSE=$(curl -s -X POST -H "Content-Type: application/json" -d "$CREATE_TICKET_DATA" "$API_GATEWAY/api/tickets")
TICKET_ID=$(echo $TICKET_RESPONSE | jq -r '.ticket.id // empty')

if [ -n "$TICKET_ID" ]; then
    echo -e "${GREEN}✓${NC} Created ticket: $TICKET_ID"
    PASSED_TESTS=$((PASSED_TESTS + 1))

    # 获取刚创建的工单
    test_endpoint "Get Ticket $TICKET_ID" "GET" "$API_GATEWAY/api/tickets/$TICKET_ID"
else
    echo -e "${RED}✗${NC} Failed to create ticket"
    FAILED_TESTS=$((FAILED_TESTS + 1))
fi
TOTAL_TESTS=$((TOTAL_TESTS + 1))
echo ""

# 4. 测试知识库服务
echo "【4. Knowledge Base】"
test_endpoint "List Knowledge Docs" "GET" "$API_GATEWAY/api/knowledge"
test_endpoint "Get Categories" "GET" "$API_GATEWAY/api/knowledge/categories"
test_endpoint "Get Popular Docs" "GET" "$API_GATEWAY/api/knowledge/popular"
echo ""

# 5. 测试分析服务
echo "【5. Analytics Service】"
test_endpoint "Get Analytics Data" "GET" "$API_GATEWAY/api/analytics"
test_endpoint "Alert Trend" "GET" "$API_GATEWAY/api/analytics/alerts/trend"
test_endpoint "Ticket Trend" "GET" "$API_GATEWAY/api/analytics/tickets/trend"
test_endpoint "Performance Metrics" "GET" "$API_GATEWAY/api/analytics/performance"
echo ""

# 6. 测试设置服务
echo "【6. Settings Service】"
test_endpoint "Get System Settings" "GET" "$API_GATEWAY/api/settings/system"
test_endpoint "Get Notification Settings" "GET" "$API_GATEWAY/api/settings/notifications"
echo ""

# 7. 测试集成服务
echo "【7. Integration Service】"
test_endpoint "List Integrations" "GET" "$API_GATEWAY/api/integrations"
test_endpoint "Get Jira Config" "GET" "$API_GATEWAY/api/integrations/jira/config"
test_endpoint "Get PagerDuty Config" "GET" "$API_GATEWAY/api/integrations/pagerduty/config"
echo ""

# 8. 测试Prometheus指标
echo "【8. Prometheus Metrics】"
METRICS_RESPONSE=$(curl -s http://localhost:8080/metrics 2>/dev/null || echo "")
if echo "$METRICS_RESPONSE" | grep -q "devops_smartbot"; then
    echo -e "${GREEN}✓${NC} Prometheus metrics available"
    PASSED_TESTS=$((PASSED_TESTS + 1))
else
    echo -e "${RED}✗${NC} Prometheus metrics not found"
    FAILED_TESTS=$((FAILED_TESTS + 1))
fi
TOTAL_TESTS=$((TOTAL_TESTS + 1))
echo ""

# 9. 检查Docker服务状态
echo "【9. Docker Services】"
SERVICES=(
    "devops-mongodb:MongoDB"
    "devops-redis:Redis"
    "devops-prometheus:Prometheus"
    "devops-grafana:Grafana"
    "devops-api-gateway:API Gateway"
    "devops-alert-service:Alert Service"
    "devops-ticket-service:Ticket Service"
    "devops-ai-gateway:AI Gateway"
    "devops-notification-service:Notification Service"
    "devops-user-service:User Service"
    "devops-integration-service:Integration Service"
)

for service in "${SERVICES[@]}"; do
    IFS=':' read -r container_name display_name <<< "$service"
    if docker ps --format '{{.Names}}' | grep -q "^${container_name}$"; then
        echo -e "${GREEN}✓${NC} $display_name is running"
        PASSED_TESTS=$((PASSED_TESTS + 1))
    else
        echo -e "${RED}✗${NC} $display_name is not running"
        FAILED_TESTS=$((FAILED_TESTS + 1))
    fi
    TOTAL_TESTS=$((TOTAL_TESTS + 1))
done
echo ""

# 10. 测试数据库连接
echo "【10. Database Connectivity】"
MONGO_TEST=$(docker exec devops-mongodb mongosh --eval "db.runCommand({ ping: 1 })" --quiet 2>/dev/null | grep -c "ok" || echo "0")
if [ "$MONGO_TEST" -gt "0" ]; then
    echo -e "${GREEN}✓${NC} MongoDB is accessible"
    PASSED_TESTS=$((PASSED_TESTS + 1))
else
    echo -e "${RED}✗${NC} MongoDB connection failed"
    FAILED_TESTS=$((FAILED_TESTS + 1))
fi
TOTAL_TESTS=$((TOTAL_TESTS + 1))

REDIS_TEST=$(docker exec devops-redis redis-cli ping 2>/dev/null || echo "")
if [ "$REDIS_TEST" = "PONG" ]; then
    echo -e "${GREEN}✓${NC} Redis is accessible"
    PASSED_TESTS=$((PASSED_TESTS + 1))
else
    echo -e "${RED}✗${NC} Redis connection failed"
    FAILED_TESTS=$((FAILED_TESTS + 1))
fi
TOTAL_TESTS=$((TOTAL_TESTS + 1))
echo ""

# 测试总结
echo "╔════════════════════════════════════════════════════════════╗"
echo "║                      测试总结                              ║"
echo "╚════════════════════════════════════════════════════════════╝"
echo ""
echo "总测试数:   $TOTAL_TESTS"
echo -e "通过:       ${GREEN}$PASSED_TESTS${NC}"
echo -e "失败:       ${RED}$FAILED_TESTS${NC}"
echo ""

SUCCESS_RATE=$((PASSED_TESTS * 100 / TOTAL_TESTS))
if [ $SUCCESS_RATE -ge 90 ]; then
    echo -e "${GREEN}✓ 测试通过率: ${SUCCESS_RATE}% - 系统运行良好！${NC}"
    exit 0
elif [ $SUCCESS_RATE -ge 70 ]; then
    echo -e "${YELLOW}⚠ 测试通过率: ${SUCCESS_RATE}% - 系统部分功能异常${NC}"
    exit 1
else
    echo -e "${RED}✗ 测试通过率: ${SUCCESS_RATE}% - 系统存在严重问题${NC}"
    exit 1
fi
